(function($) {
	$.fn.extend({
		// 检查一个dom是否为显示
		isShow : function(){
			if($(this).css("display") == "none"){
				return false;
			}else{
				return true;
			}
		}
	});
	$.getUrlParam = function(name) {
		var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r!=null) return unescape(r[2]); return null;
	};
})(jQuery);

var ajaxRequest = function(method, url, param, fnSuccess, fnError, before, after, async) {
	$J.ajax({
		type : method,
		url : url,
		dataType : 'json',
		contentType: 'application/json;charset=UTF-8',
		async : async ? async : true,
		data : param,
		beforeSend : function() {
			if (before)
				before();
		},
		success : function(data) {
			if(data && data.status == false) {
				if (fnError) {
					fnError(data.msg);
				} else {
					Dialog.timeout(data.msg);
				}
				return;
			}
			fnSuccess(data.data);
		},
		error : function(data) {
			if (fnError) {
				fnError(data.msg);
			} else {
				Dialog.warning("当前服务器繁忙，请稍候再试...");
			}
		},
		complete: function() {
			if (after)
				after();
		}
	});
};

var ajaxPost = function(url,param,fnSuccess,fnError,before,after,async){
	ajaxRequest('post',url,param,fnSuccess,fnError,before,after,async);
};

function ajaxGet(url,param,fnSuccess,fnError,before,after,async){
	ajaxRequest('get',url,param,fnSuccess,fnError,before,after,async);
};

var ajaxPut = function(url,param,fnSuccess,fnError,before,after,async){
	ajaxRequest('put',url,param,fnSuccess,fnError,before,after,async);
};


/**
 * ResponseData 对象
 * 
 * @param code
 * @param message
 * @param data
 * @returns {Response}
 */
function Response(code, message, data) {
	this.code = code;
	this.message = message;
	this.data = data;
	this.result = (this.code == Response.SUCCEED);
}
/**
 * ResponseData 对象构造工具
 */
Response.getInstance = function(json) {
	if (json) {
		var info = new Response(json.status, json.msg, json.data);
		return info;
	}
	return null;
}
Response.SUCCEED = 200;
Response.FAILED = -1;

/**********************
 * 省市区县数据操作
 **********************/

/**
 * 获取省市区县数据
 */
var Province = {
		allProvince : null,
		allCity : null,
		allDistrict : null
};

/**
 * 获取所有的省市地区数据。
 * @param callback 回调函数(相应结果-boolean)
 */
Province.getData = function(callback) {
	if (Province.allProvince && Province.allCity && Province.allDistrict)
		callback(true);
	
	var uri = window.baseUrl + "/area";
	var param = {};
	var success = function (data) {
		Province.allProvince = data.province;
		Province.allCity = data.city;
		Province.allDistrict = data.district;
		callback(status);
	};
	ajaxGet(uri, param, success);
}

Province.searchCity = function(provinceId) {
	var citys = [];
	if (Province.allCity && Province.allCity.length > 0) {
		for (var i = 0; i < Province.allCity.length; i++) {
			var entry = Province.allCity[i];
			if (entry.provinceId == provinceId) {
				citys.push(entry);
			}
		}
	}
	return citys;
}

Province.searchDistrict = function(cityId) {
	var rs = [];
	if (Province.allDistrict && Province.allDistrict.length > 0) {
		for (var i = 0; i < Province.allDistrict.length; i++) {
			var entry = Province.allDistrict[i];
			if (entry.cityId == cityId) {
				rs.push(entry);
			}
		}
	}
	return rs;
}

Province.searchCityById = function(cityId) {
	if (Province.allCity && Province.allCity.length > 0) {
		for (var i = 0; i < Province.allCity.length; i++) {
			var entry = Province.allCity[i];
			if (entry.id == cityId) {
				return entry;
			}
		}
	}
}

/**********************
 * String Utils
 **********************/

var StringUtils = {};
StringUtils.isBlank = function(string) {
	return string === undefined || string == "" || $J.trim(string) == "";
}
StringUtils.isNotBlank = function(string) {
	return !StringUtils.isBlank(string);
}

/**********************
 * Dom Utils
 **********************/
var Dom = {};
Dom.getNoDataTD = function(colspan) {
	var trip = '<div class="ui-tiptext-container ui-tiptext-container-warning">'+
					'<p class="ui-tiptext ui-tiptext-warning">'+
						'<em class="ui-tiptext-icon iconfont" title="警告"></em>'+
						'暂时没有找到符合条件的内容。'+
					'</p>'+
				'</div>';
	var li = $J("<tr control-name='nodata' />");
	li.append("<td colspan='" + colspan + "'>"+trip+"</td>");
	return li;
}

/**********************
 * Dialog Utils
 **********************/
var Dialog = {
		defaultLayout : "topCenter"
};
Dialog.success = function(text, fn) {
	var ui = Dialog.create(text, "success", Dialog.defaultLayout, 4000, fn);
}
Dialog.error = function(text, fn) {
	var ui = Dialog.create(text, "error", Dialog.defaultLayout, 3000, fn);
}
Dialog.warning = function(text, fn) {
	var ui = Dialog.create(text, "warning", Dialog.defaultLayout, 3000, fn);
}
Dialog.timeout = function(text, fn) {
	var ui = Dialog.create(text, "warning", Dialog.defaultLayout, 3000, fn);
}
Dialog.create = function(text, type, layout, timeout, fn) {
	$J.noty({
		layout : layout,
		text : text,
		type : type,
		timeout : timeout,
		afterClose: function() {
			if(fn){
				fn();
			}
		}
	});
}

function getDate(count){
	var date = new Date();
	var allDays = [];
	for (var i = 0; i < parseInt(count); i++) {
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		var day = date.getDate() + parseInt(i > 0 ? i : 0);
		allDays.push({
			"id": i,
			"name": year + "-" + month + "-" + day
		});
	}
	return allDays;
}

/**********************
 * Cookie Utils
 **********************/

var Cookie = {
		KEY_SEND_SMS_TIME : "Send.SMS.Time_"
};

Cookie.cookie = function() {
	var cookieArray = document.cookie.split(";"); // 得到分割的cookie名值对
	var cookie = new Object();
	for ( var i = 0; i < cookieArray.length; i++) {
		var arr = cookieArray[i].split("="); // 将名和值分开
		if (arr[0] == name)
			return unescape(arr[1]); // 如果是指定的cookie，则返回它的值
	}
	return "";
}

Cookie.getCookie = function(objName) {// 获取指定名称的cookie的值
	var arrStr = document.cookie.split("; ");
	for ( var i = 0; i < arrStr.length; i++) {
		var temp = arrStr[i].split("=");
		if (temp[0] == objName)
			return unescape(temp[1]);
	}
}

Cookie.addCookie = function(objName, objValue, objHours) { // 添加cookie
	var str = objName + "=" + escape(objValue);
	if (objHours > 0) { // 为时不设定过期时间，浏览器关闭时cookie自动消失
		var date = new Date();
		var ms = objHours * 3600 * 1000;
		date.setTime(date.getTime() + ms);
//		console.log(date);
		str += "; expires=" + date.toGMTString() + ";path=/";
	}
	document.cookie = str;
}

Cookie.setCookie = function(name, value)// 两个参数，一个是cookie的名子，一个是值
{
	var Days = 30; // 此 cookie 将被保存 30 天
	var exp = new Date(); // new Date("December 31, 9998");
	exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
	document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
}

Cookie.getCookie = function(name)// 取cookies函数
{
	var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
	if (arr != null)
		return unescape(arr[2]);
	return null;
}

Cookie.delCookie = function(name)// 删除cookie
{
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = getCookie(name);
	if (cval != null)
		document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

/**********************
 * SMS Utils
 **********************/

var SMS = {};
SMS.send = function(cellphone) {
	Cookie.setCookie(Cookie.KEY_SEND_SMS_TIME + cellphone, new Date().getTime());
}

SMS.get = function(cellphone) {
//	console.log("SMS.get:" + cellphone);
	return Cookie.getCookie(Cookie.KEY_SEND_SMS_TIME + cellphone);
}

/**********************
 * Button Utils
 **********************/
var Btn = {};
Btn.disabled = function(btn) {
	$J(btn).unbind();
	$J(btn).attr("disabled", true);
	$J(btn).attr("class", "ui-button ui-button-ldisable");
};
Btn.enabled = function(btn, event, handler) {
	$J(btn).unbind();
	$J(btn).attr("disabled", false);
	$J(btn).attr("class", "ui-button ui-button-lblue");
	$J(btn).bind(event, handler);
};
Btn.enabledClick = function(btn, handler) {
	Btn.enabled(btn, "click", handler);
}

/*************************
 * 日期
 * ***********************/
Date.prototype.Format = function (fmt) { 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
